import * as vscode from 'vscode';
export function getConfig<T>(key: string, v?: T) {
	return vscode.workspace.getConfiguration().get(key, v);
}

export function getConfigs(ctx: vscode.ExtensionContext) {
	return {
		extensionPath: ctx.extensionPath,
		quality: getConfig('VscodeBrowser.quality', 100),
		chromeExecutable: getConfig('VscodeBrowser.chromeExecutable'),
		startUrl: getConfig('VscodeBrowser.startUrl', 'https://bilibili.com'),
		proxy: getConfig('VscodeBrowser.proxy', ''),
	};
}
export async function createBrowserClient(context: vscode.ExtensionContext, url: string | undefined) {
	const config = getConfigs(context);
	url = url ?? config.startUrl;
	let panel = vscode.window.createWebviewPanel('browser', 'Browser', vscode.ViewColumn.Two, {
		enableScripts: true,
		enableCommandUris: true,
		retainContextWhenHidden: true,
		enableFindWidget: true,
		localResourceRoots: [vscode.Uri.file(config.extensionPath)],
	});

	// let content = await fetchWebContent(url);
	panel.webview.html = await getWebviewContent(url);

	panel.webview.onDidReceiveMessage(
		async (message) => {
			switch (message.command) {
				case 'loadUrl':
					let content = await fetchWebContent(message.url);
					panel.webview.html = await getWebviewContent(message.url, content);
					break;
				case 'alert':
					vscode.window.showInformationMessage(message.text);
					break;
				case 'urlChanged':
					let changedUrl = message.url;
					content = await fetchWebContent(changedUrl);
					panel.webview.html = await getWebviewContent(changedUrl, content);
					vscode.window.showInformationMessage('url changed to ' + message.url);
					break;
				case 'openFile':
					const uri = vscode.Uri.parse(message.path);
					const doc = await vscode.workspace.openTextDocument(uri);
					const editor = await vscode.window.showTextDocument(doc);
					editor.revealRange(new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 0)));
					break;

				case 'openFolder':
					const folderUri = vscode.Uri.parse(message.path);
					await vscode.commands.executeCommand('vscode.openFolder', folderUri);

					break;
				case 'openWorkspace':
					const workspaceUri = vscode.Uri.parse(message.path);
					await vscode.commands.executeCommand('vscode.openWorkspace', workspaceUri);
					break;
				case 'openTerminal':
					const terminal = vscode.window.createTerminal();
					terminal.sendText(message.path);
					break;
				case 'openCommand':
					await vscode.commands.executeCommand(message.commandId, message.args);
					break;

				case 'openUrl':
					vscode.env.openExternal(vscode.Uri.parse(message.url));
					break;
				case 'reload':
					panel.webview.html = await getWebviewContent(url);
					break;

				case 'openPreview':
					const previewUri = vscode.Uri.parse(message.path);
					const previewDoc = await vscode.workspace.openTextDocument(previewUri);
					const previewEditor = await vscode.window.showTextDocument(previewDoc, { preview: true });
					previewEditor.revealRange(new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 0)));
					break;

				case 'openSettings':
					await vscode.commands.executeCommand('workbench.action.openSettings');
					break;
				case 'openExtensions':
					await vscode.commands.executeCommand('workbench.extensions.action.showExtensionsAssistant');
					break;

				default:
					break;
			}
		},
		undefined,
		context.subscriptions,
	);
}

async function fetchWebContent(url: string | undefined): Promise<string> {
	try {
		if (url) {
			const response = await fetch(url);
			const html = await response.text();
			// vscode.window.showInformationMessage(html);
			return html;
		}
		return `<p>Error loading ${url}: No URL provided</p>`;
	} catch (error) {
		return `<p>Error loading ${url}: ${error}</p>`;
	}
}
// }
// function getContent(url, webview) {
// 	// const root = join(this.config.extensionPath, 'dist/client')
// 	// const indexHTML = fs.readFileSync(join(root, 'index.html'), 'utf-8')
// 	const indexHtml = getWebviewContent(url);
// 	return indexHtml.replace(
// 		/(src|href)="(.*?)"/g,
// 		(_, tag, url) => `${tag}="${webview.asWebviewUri(vscode.Uri.file(join(url.slice(1))))}"`,
// 	);
// }
async function getWebviewContent(url?: string | undefined, content: string = '') {
	return `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Browser</title>
            <style>
				 body { margin: 0; font-family: Arial, sans-serif  ; margin:0 ; padding:0 ; overflow:hidden; display :flex ;    flex-direction: column;   height :100vh } 
             iframe { width: 100%; height: 100%; flex:1 ;margin :0; border: none: 
			 padding:0;    } 
			   
			 
			   .toolbar {
			    display: flex; 
            align-items: center;
            background-color: #32485b;
            
        }
        .refresh  , .leftArrow, .rightArrow {
		      margin-left : 3px;
            margin-right: 3px;
            background: none;
            border: none;
            cursor: pointer;
            color: white;
            font-size: 1.5em;
			    margin-top:10px;
      &:hover {
              opacity: 0.7;
                         
      }
        }
        .urlbar {
           box-sizing: border-box; /* 确保 padding 和 border 包含在宽度内 */
            padding: 8px;
            flex:1 ;
               align-items: center;
               width :300px ;
            margin-left: 60px     !important;
            margin-bottom: 5px   !important;
            margin-top: 5px      !important;
            border: none;
            border-radius: 4px;
            font-size: 1em;
            background-color: inherit;
            color: white;
			
        }
            </style>
			<link  rel="stylesheet"  href="./toolsBar.css"> 
        </head>
        <body>
		<div class="toolbar">
        <div class="inner"  onclick="returnBack()">
       
        <button  class="rightArrow" onclick="returnForward()">
         <svg width="1em" height="1em" viewBox="0 0 32 32" ><path d="M18 6l-1.43 1.393L24.15 15H4v2h20.15l-7.58 7.573L18 26l10-10L18 6z" fill="currentColor"></path></svg>
        </button>
          <button
            class="refresh"
            onClick="pageRefresh()"
          >
            <svg width="1em" height="1em" viewBox="0 0 32 32" >
      <path d="M12 10H6.78A11 11 0 0 1 27 16h2A13 13 0 0 0 6 7.68V4H4v8h8z" fill="currentColor"></path>
      <path d="M20 22h5.22A11 11 0 0 1 5 16H3a13 13 0 0 0 23 8.32V28h2v-8h-8z" fill="currentColor"></path>
      </svg>
          </button>
          <input
          class="urlbar"
          type="text"
          value="localhost"
          onchange="handleInput(event)"
          onKeyDown="handleKeyDown(event)"
        />
        </div>
      </div>
      </div>
             <iframe  src=${url}  id="myFrameId"  loading="lazy"  allowfullscreen
			 >
			 </iframe> 
			 <div>${content}</div>
        </body>   
		<script> 
    function checkUrlResult() {
         const iframe = document.getElementById('myFrameId');

          iframe.onload = function() {
                console.log('Iframe content loaded successfully.');
                return true ; 
            };

            // 监听 onerror 事件
            iframe.onerror = function() {
                iframe.contentDocument.open();
                iframe.contentDocument.write(\`${content.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\`);
                iframe.contentDocument.close();
                console.error('Error loading iframe content.'); 
                return false ; 

            }; 
}
  checkUrlResult() ; 
          function handleKeyDown(event) {
                if (event.keyCode === 13) {
                  let url = event.target.value.trim();  
				  if(!url.startsWith('http://') && !url.startsWith('https://')) {
                    url = 'http://' + url; 
                    if(!url.endsWith('.com') && !url.includes('localhost') &&!url.includes('127.0.0.1'))  {url += '.com';    }
                  } 
                    checkUrlResult() ;  
                    event.target.value = url; 
                  document.getElementById('myFrameId').src = url;
                  vscode.postMessage({ command: 'urlChanged', url: url });
  			   }
           }

        // Function to navigate to the URL in the address bar
        // function navigate() {
        //   const url = addressBar.value;
        //   contentFrame.src = url;
        //   vscode.postMessage({ command: 'urlChanged', url: url });
        // }

        // Function to refresh the page 
		  function  pageRefresh() { 
		   document.getElementsById('myFrameId').src = document.getElementsById('myFrameId').src;
		  }

        // Handle messages from the extension
        // window.addEventListener('message', (event) => {
        //   const message = event.data;
        //   if (message.command === 'setUrl') {
        //     addressBar.value = message.url;
        //     contentFrame.src = message.url;
        //   }
        // });
        function returnBack() { 
          document.getElementsById('myFrameId').src = document.getElementsById('myFrameId').src;
        } 
		 </script>
        </html>
    `;
}
